/**
 * 
 */
package info.niwota.fwrite;

import info.niwota.commons.web.JsonObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qiangli
 *
 */
public class DocumentHelper {
	private static long seq = System.currentTimeMillis();

	private static Document TOP = null;
	
	static {
		File topdir = SDCard.getTopDir();
		File topfile = new File(topdir.getPath()+Document.FILE_EXT);
		TOP = new Document(topfile);
		TOP.load();
	}
	
	private static long nextId() {
		return ++seq;
	}
	
	private DocumentHelper() {
	}

	public static List<Document> listTop() {
		return list(null);
	} 
	
	public static List<Document> list(Document parent) {
		File top = SDCard.getTopDir();
		ArrayList<Document> notes = new ArrayList<Document>();
		File f = (parent == null ? null : parent.getSubfolder());
		if (f == null) {
			f = top;
		}
		
		if (f != null && f.exists()) {
			String[] names = f.list(Document.filter);
			if (names != null && names.length > 0) {
				for (int i = 0; i < names.length; i++) {
					try {
						Document d = new Document(new File(f, names[i]));
						d.load();
						notes.add(d);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return notes;
	}
	
	
	synchronized public static Document add(final Document doc) throws Exception { 
		File dir = (doc.getSubfolder());
	
		if (!dir.exists()) {
			dir.mkdirs();
		}
		
		File file = null;
		long id = -1;
		while(true) {
			id = nextId();
			file = new File(dir, id + Document.FILE_EXT);
			if (!file.exists()) {
				break;
			}
		}
	
		JsonObject jo = new JsonObject();
		
		jo.put(Document.KEY_ID, id);
		jo.put(Document.KEY_FLAG, Document.FLAG_DEFAULT);
		final long now = System.currentTimeMillis();
		jo.put(Document.KEY_CREATED, now);
		jo.put(Document.KEY_MODIFIED, now);
		
		Document d = new Document(file);
		d.update(jo);
		
		return d;
	}

	public static List<Document> createBreadCrumb(final Document doc) {
		List<Document> docs = new ArrayList<Document>();
		docs.add(TOP); 
		if (doc != null) {
			Document d = doc;
			while ((d = d.getParentDocument()) != null) {
				docs.add(d);
			}
		}
		return docs;
	}

}
